package SlidingWindow;

import java.util.HashMap;

/**
 * @ClassName LC1234
 * @Description TODO
 * @Author ZJX
 * @Date 2024/9/21 19:55
 * @Version 1.0
 */
public class LC1234 {
    public int balancedString(String s) {
//        用 map 记录每个字符出现的次数
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('Q',0);
        map.put('W',0);
        map.put('E',0);
        map.put('R',0);

//         计算每个字符的出现次数
        for(char c : s.toCharArray()){
            map.put(c, map.get(c) + 1);
        }

        int n  = s.length();
        int target = n / 4;
        if (map.get('Q') == target && map.get('W') == target && map.get('E') == target && map.get('R') == target){
            return 0;
        }

        int minLength = n;
        int left = 0;
        for (int right = 0; right < n; right++) {
            char ch = s.charAt(right);
            map.put(ch,map.get(ch) - 1);

            // 当窗口中的所有字符都满足不超过 target 的要求时，尝试收缩窗口
            while (map.get('Q') <= target && map.get('W') <= target && map.get('E') <= target && map.get('R') <= target) {
                minLength = Math.min(minLength,right - left + 1);

                // 收缩窗口，恢复左边界字符的计数
                char leftChar = s.charAt(left);
                map.put(leftChar, map.get(leftChar) + 1);
                left++;
            }
        }
        return minLength;
    }
}
